// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTJOBCOLLECTION } from './store/actions/pagejobcollection'
import { UPDATEPAGEJOBCOLLECTION } from './store/types/pagejobcollection'
// less
import './index.less'

import NetworkError from '../../components/taro-ui/network-error'
import { showToast } from '../../crossplatform/apiservice/toast'
import TitleShowClear from './components/title-show-clear'
import JobListItem from '../../components/page-components/job-list-item'
import If from '../../components/page-components/if'
import ShowEmpty from '../../components/page-components/show-empty'
import Dialog from '../../components/page-components/dialog'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import { removePostRequest } from '../../service/archive-operate-controller'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEJOBCOLLECTION,
      payload: {
        ...payload
      }
    })
  },
  dorequest(payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTJOBCOLLECTION(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagejobcollection, userinfo, landmark }) => ({
    ...pagejobcollection,
    userId: userinfo.zhichuUserId,
    companyId: userinfo.companyId,
    role: userinfo.role,
    landmarkName: landmark.landmarkName
  }),
  mapActiontoProps
)
class JobCollection extends Component {
  config = {
    navigationBarTitleText: '职位收藏'
  }
  static defaultProps = {
    dataSource: []
  }

  constructor(props) {
    super(props)
    this.state = {
      bottomVisible: false,
      modalVisible: false
    }
  }
  componentWillMount() {
    // onLoad
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    this.queryWrap()
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  queryWrap = () => {
    const { userId } = this.props
    this.props.dorequest({ userId })
  }

  onReload = () => {
    this.queryWrap()
  }

  callbackRequest = () => {
    this.queryWrap()
  }

  onExtraTap = () => {
    // 点击管理
    const { bottomVisible } = this.state
    this.setState({
      bottomVisible: !bottomVisible
    })
  }

  onTapCheckItem = e => {
    // 点击选择
    const { index, id, isOld } = e.currentTarget.dataset
    const { bottomVisible } = this.state
    const { dataSource = [] } = this.props
    if (bottomVisible) {
      this.props.updateState({
        dataSource: dataSource.map((e, i) =>
          i === index
            ? {
                ...e,
                checked: !e.checked
              }
            : e
        )
      })
    } else {
      if (!isOld) {
        navigateTo({
          url: `${pagejumplist['job-detail'].path}?id=${id}&isCollect=1`
        })
      } else {
        // 老数据
        navigateTo({
          url: `${pagejumplist['job-detail'].path}?id=${id}&isOld=${isOld}&isCollect=1`
        })
      }
    }
  }

  onCheckAll = () => {
    // 点击全选
    let { dataSource = [] } = this.props
    const checkCount = dataSource.filter(e => e.checked).length
    dataSource = dataSource.map(e => ({
      ...e,
      checked: checkCount !== dataSource.length
    }))
    this.props.updateState({
      dataSource
    })
  }

  onDelete = () => {
    // 点击删除 显示弹窗
    const { dataSource } = this.props
    const checkedImgArr = dataSource.filter(e => e.checked)
    if (checkedImgArr.length) {
      this.setState({
        modalVisible: true
      })
    } else {
      showToast({
        title: '请选择'
      })
    }
  }

  onDeleteOk = () => {
    const { dataSource } = this.props
    const checkedImgArr = dataSource.filter(e => e.checked).map(e => e.id)
    removePostRequest({ ids: checkedImgArr }).then(({ data }) => {
      if (data.code) {
        this.queryWrap()
        this.setState({
          bottomVisible: false,
          modalVisible: false
        })
      } else {
        showToast({
          title: '删除失败！'
        })
      }
    })
  }

  onDeleteCancel = () => {
    // 取消删除
    this.setState({
      modalVisible: false
    })
  }

  render() {
    const { dataSource = [], landmarkName } = this.props
    const { bottomVisible, modalVisible } = this.state
    const checkAll = dataSource.every(e => e.checked)
    return (
      <View className="JobCollection_id11136">
        <NetworkError visible={this.props.networkerror} onReload={this.onReload} />
        <View className={`JobCollection_id11136Wrap ${this.props.networkerror ? 'hide' : ''}`}>
          <TitleShowClear
            name="职位收藏"
            extra={`${dataSource.length > 0 ? 'clear' : ''}`}
            extraName={!bottomVisible ? '管理' : '取消'}
            onExtraTap={this.onExtraTap}
            number={dataSource.length || 0}
          />
          <If visible={dataSource.length} renderElse={<ShowEmpty />}>
            <View className={`job-check-container ${bottomVisible ? 'job-check' : ''}`}>
              {dataSource.map((data, index) => {
                return (
                  <View
                    className={`job-container ${bottomVisible ? 'job-container-check' : ''}`}
                    key={index}
                    data-index={index}
                    data-id={data.postId}
                    data-isOld={data.isOld}
                    onClick={this.onTapCheckItem}
                  >
                    <If visible={bottomVisible}>
                      <If visible={data.checked} renderElse={<View className="no-check" />}>
                        <Image
                          className="bottom-img"
                          src="https://imagesize.hrwork.com/sp/files/5f5130a2-c900-42a6-ba80-aab3b01770a1.png"
                        />
                      </If>
                    </If>
                    <JobListItem
                      data={data}
                      landmarkName={landmarkName}
                      formSubmit={this.formSubmit}
                      showDate
                    />
                  </View>
                )
              })}
            </View>
          </If>
        </View>

        <If visible={bottomVisible}>
          <View className="bottom-btn">
            <View className="bottom-left" onClick={this.onCheckAll}>
              <If visible={checkAll} renderElse={<View className="no-check" />}>
                <Image
                  src="https://imagesize.hrwork.com/sp/files/5f5130a2-c900-42a6-ba80-aab3b01770a1.png"
                  className="bottom-img"
                />
              </If>
              <View className="left-text">{checkAll ? '取消全选' : '全选'}</View>
            </View>
            <View className="bottom-right" onClick={this.onDelete}>
              删除
            </View>
          </View>
        </If>

        <AtActionSheet isOpened={modalVisible}>
          <Dialog
            title="提醒"
            subtext="确定要删除所选岗位吗？"
            leftText="取消"
            rightText="删除"
            onOk={this.onDeleteOk}
            onLeftOk={this.onDeleteCancel}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default JobCollection
